import os
import subprocess as sub
from wsgiref.simple_server import make_server

from monitor_lib import cpu, ram, hd, default_worker


def find_worker(path_info):
    # 这里的get 方法是字典的方法，用来根据path_info的值，
    # 取出相应的响应方法，如果path_info在字典中找不到，
    # 就使用默认值default_worker。
    worker = url_worker_mapping.get(path_info, default_worker)
    return worker


def app(env, callback):
    worker = find_worker(env['PATH_INFO'])
    # 每一个worker函数必须返回一个元组。
    # 然后把元组的元素拆出来，赋值给三个变量。
    # 元组赋值法
    status, headers, body = worker(env)
    callback(status, headers)
    return [body]


url_worker_mapping = {
    '/monitor/cpu': cpu,
    '/monitor/ram': ram,
    '/monitor/hd': hd,
}


if __name__ == '__main__':
    host = 'localhost'
    port = 8000
    print('serving on %s:%s' % (host, port))
    httpd = make_server(host, port, app)
    httpd.serve_forever()
